#include "widget.h"
#include "ui_widget.h"

#include <QComboBox>
#include <QLabel>
#include <QMessageBox>
#include <QPainter>
#include <QPropertyAnimation>
#include <QTimer>

#include <QtNetwork/QHostAddress>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    // 设置窗口标题
    setWindowTitle(QString("雷达检测"));

    QPixmap pixmap = QPixmap(":/new/prefix1/main_backgroud.jpg").scaled(this->size());
    QPalette palette(this->palette());
    palette.setBrush(QPalette::Window, QBrush(pixmap));
    this->setPalette(palette);


    // 主体布局
    mainLayout = new QHBoxLayout(this);

    // 左右面板
    leftPanel = createLeftPanel();
    leftPanel->setStyleSheet("background-color: rgba(255, 255, 255, 10);");
    rightPanel = createRightPanel();
    rightPanel->setStyleSheet("background-color: rgba(255, 255, 255, 10);");

    rightPanel->setMinimumSize(400,400);
    mainLayout->addWidget(leftPanel, 2);  // 左侧占比小
    mainLayout->addWidget(rightPanel, 5); // 右侧占比较大

    this->setLayout(mainLayout);
    // connect(tcpServer, &QTcpServer::newConnection, this, &Widget::newConnection);


}

Widget::~Widget()
{
    delete ui;
}



void Widget::closeEvent(QCloseEvent *event)
{
    int ret = QMessageBox::question(this, QString("关闭"), \
                                    QString("你确定要关闭吗"),\
                                    QMessageBox::Yes, QMessageBox::No);
    if(QMessageBox::Yes == ret){
        event->accept();
    }else{
        event->ignore();
    }
}

QWidget *Widget::createLeftPanel()
{
    leftWidget = new QWidget();
    leftLayout = new QVBoxLayout(leftWidget);

    // 添加雷达站点信息容器
    stationInfo = createStationInfoWidget();
    leftLayout->addWidget(stationInfo, 4);

    // 第二容器：武器选择区域
    leftLayout->addWidget(createWeaponControlPanel(), 3);

    // 第三容器：滚动雷达信息列表
    leftLayout->addWidget(createScrollingInfoList(), 4);

    return leftWidget;
}



QWidget *Widget::createRightPanel()
{
    rightPanel = new QWidget();

    rightLayout = new QVBoxLayout(rightPanel);

    radar = new Radar(this);
    rightLayout->addWidget(radar);
    connect(radar, &Radar::updatePointData, this, &Widget::updatePointData);

    // 初始化定时器
    m_updateTimer = new QTimer(this);
    connect(m_updateTimer, &QTimer::timeout, [this](){
        m_scanAngle = (m_scanAngle + 2) % 360;
        // updateTargets();
        radar->updateScanAngle(m_scanAngle);
    });
    m_updateTimer->start(50); // 20 FPS

    return rightPanel;
}



QWidget *Widget::createStationInfoWidget()
{
    QWidget *stationInfoWidget = new QWidget();
    QHBoxLayout *stationInfoLayout = new QHBoxLayout(stationInfoWidget);

    // 右侧信息块
    infoLayout = new QVBoxLayout();

    stationName = new QHBoxLayout();
    status = new QLabel("存活状态：🟢 正常运行");
    personnel = new QLabel("人员数量：12 人");

    QFont station_font("Microsoft YaHei", 10);
    QString stationLabel_Style = "color: #333;border-radius:5px;padding: 4px; border: 1px solid #aaa;";
    QString stationCombo_Style = "QComboBox { background-color: rgba(255, 255, 255, 50);padding: 4px; border: 1px solid #aaa; border-radius: 4px; }";
    QString btn_Style = "QPushButton { background-color: rgba(0, 0, 255, 50); color: white; border: none; "
                          "padding: 6px 12px; border-radius: 4px; }"
                          "QPushButton:hover { background-color: #005A9E; }";


    stationLabel = new QLabel("基站");
    stationLabel->setFont(station_font);
    stationLabel->setStyleSheet(stationLabel_Style);
    stationCombo = new QComboBox();
    stationCombo->addItems({"8888", "1234", "9870"});
    stationCombo->setStyleSheet(stationCombo_Style);
    stationName->addWidget(stationLabel);
    stationName->addWidget(stationCombo);

    status->setAlignment(Qt::AlignCenter);
    // status->setFixedHeight(50);
    personnel->setAlignment(Qt::AlignCenter);
    // personnel->setFixedHeight(50);

    status->setFont(station_font);
    personnel->setFont(station_font);

    // stationName->setStyleSheet("color: #333;");
    status->setStyleSheet("color: green;");
    personnel->setStyleSheet("color: #333;");

    // 按键
    QFont btn_font("Microsoft YaHei", 10, QFont::Bold);

    btnLayout = new QHBoxLayout();
    con_btn = new QPushButton("请求连接");
    con_btn->setStyleSheet(btn_Style);
    con_btn->setFont(btn_font);
    con_btn->setFixedHeight(28);
    con_btn->setCursor(Qt::PointingHandCursor);
    con_btn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    close_btn = new QPushButton("断开连接");
    close_btn->setStyleSheet(btn_Style);
    close_btn->setFont(btn_font);
    close_btn->setFixedHeight(28);
    close_btn->setCursor(Qt::PointingHandCursor);
    close_btn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    btnLayout->addWidget(con_btn);
    btnLayout->addWidget(close_btn);

    connect(con_btn, &QPushButton::clicked, this, &Widget::on_con_btn_clicked);
    connect(close_btn, &QPushButton::clicked, this, &Widget::on_close_btn_clicked);

    // infoLayout->addWidget(stationName);
    infoLayout->addLayout(stationName);
    infoLayout->addWidget(status);
    infoLayout->addWidget(personnel);
    infoLayout->addLayout(btnLayout);

    stationInfoLayout->addLayout(infoLayout);
    stationInfoLayout->setContentsMargins(5, 5, 5, 5);

    stationInfoWidget->setStyleSheet("background-color: rgba(255, 255, 255, 70);");

    return stationInfoWidget;
}


QWidget * Widget::createWeaponControlPanel()
{
    weaponPanel = new QWidget();
    weaponlayout = new QVBoxLayout(weaponPanel);
    weaponlayout->setContentsMargins(10, 0, 10, 0); // 左 * 右 *
    weaponlayout->setSpacing(2);

    QFont labelFont("Microsoft YaHei", 10);
    QString labelStyle = "color: #333;border-radius:5px;padding: 4px; border: 1px solid #aaa;";
    QString comboStyle = "QComboBox { background-color: rgba(255, 255, 255, 50);padding: 4px; border: 1px solid #aaa; border-radius: 4px; }";
    QString buttonStyle = "QPushButton { background-color: rgba(0, 0, 255, 50); color: white; border: none; "
                          "padding: 6px 12px; border-radius: 4px; }"
                          "QPushButton:hover { background-color: #005A9E; }";

    // 武器选择
    row1 = new QHBoxLayout();
    weaponLabel = new QLabel("武器");
    // weaponLabel->setAlignment(Qt::AlignCenter);
    weaponLabel->setFont(labelFont);
    weaponLabel->setStyleSheet(labelStyle);
    weaponCombo = new QComboBox();
    weaponCombo->addItems({"导弹", "火箭弹", "激光炮"});
    weaponCombo->setStyleSheet(comboStyle);
    row1->addWidget(weaponLabel);
    row1->addWidget(weaponCombo);

    // 发射按钮
    fireBtn = new QPushButton("发射");
    fireBtn->setStyleSheet(buttonStyle);
    fireBtn->setFont(QFont("Microsoft YaHei", 10, QFont::Bold));
    fireBtn->setFixedHeight(28); // 减小高度
    fireBtn->setCursor(Qt::PointingHandCursor);
    fireBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); // 宽度自动填满
    // connect(fireBtn, &QPushButton::clicked, this, &Widget::deletePointInMap);
    connect(fireBtn, &QPushButton::clicked, this, &Widget::deletePointInMap);


    // 目标点信息
    ImLable = new QLabel();
    ImLable->setAlignment(Qt::AlignCenter);
    ImLable->setStyleSheet("background-color: rgba(255, 255, 255, 50); border:1px solid #ccc; border-radius:5px; padding:4px;");


    // 添加到主布局
    weaponlayout->addLayout(row1);
    weaponlayout->addWidget(ImLable);
    weaponlayout->addWidget(fireBtn);

    // 容器样式
    weaponPanel->setStyleSheet("background-color: rgba(255, 255, 255, 50);");

    return weaponPanel;
}

QWidget * Widget::createScrollingInfoList()
{
    scrollArea = new QScrollArea();
    scrollArea->setWidgetResizable(true);
    scrollArea->setFixedHeight(150); // 高度你可以自调

    // 隐藏滚动条
    scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    scrollContent = new QWidget();
    scrollLayout = new QVBoxLayout(scrollContent);
    scrollLayout->setSpacing(10);
    scrollLayout->setContentsMargins(5, 5, 5, 5);

    scrollContent->setLayout(scrollLayout);
    scrollArea->setWidget(scrollContent);

    startScrollTimer(); // 启动滚动

    return scrollArea;
}



void Widget::startScrollTimer()
{
    scrollTimer = new QTimer(this);
    connect(scrollTimer, &QTimer::timeout, this, [=]() {
        if (!scrollLayout || scrollLayout->count() <= 1) return;

        QWidget *firstItem = scrollLayout->itemAt(0)->widget();

        // 动画向上滚动
        QPropertyAnimation *anim = new QPropertyAnimation(firstItem, "geometry");
        QRect startRect = firstItem->geometry();
        QRect endRect = QRect(startRect.x(), startRect.y() - startRect.height() - scrollLayout->spacing(),
                              startRect.width(), startRect.height());
        anim->setDuration(500);
        anim->setStartValue(startRect);
        anim->setEndValue(endRect);
        anim->start(QAbstractAnimation::DeleteWhenStopped);

        // 动画结束后将第一个元素移到最后
        connect(anim, &QPropertyAnimation::finished, this, [=]() {
            scrollLayout->removeWidget(firstItem);
            scrollLayout->addWidget(firstItem);
            firstItem->show();
        });
    });

    scrollTimer->start(2000); // 每2秒滚动一次
}


void Widget::on_con_btn_clicked()
{
    cnt = new Connect();
    cnt->show();
    connect(cnt, &Connect::pointDataReceived, this, &Widget::updateRadarData);
}

void Widget::on_close_btn_clicked()
{
    cnt->stopListening();
    cnt->close();
}

QString Widget::convertDirection(qreal angleRadian)
{
    double angleDeg = angleRadian * 180.0 / M_PI;  // 弧度转角度
    angleDeg = fmod(angleDeg + 360.0, 360.0);       // 保证是 [0, 360) 范围

    // 方向划分（可按需精细划分）
    if (angleDeg >= 0 && angleDeg < 45)
        return QString("正东%1").arg(int(angleDeg));
    else if (angleDeg < 90)
        return QString("东偏南%1").arg(int(angleDeg - 45));
    else if (angleDeg < 135)
        return QString("正南%1").arg(int(angleDeg - 90));
    else if (angleDeg < 180)
        return QString("西偏南%1").arg(int(angleDeg - 135));
    else if (angleDeg < 225)
        return QString("正西%1").arg(int(angleDeg - 180));
    else if (angleDeg < 270)
        return QString("西偏北%1").arg(int(angleDeg - 225));
    else if (angleDeg < 315)
        return QString("正北%1").arg(int(angleDeg - 270));
    else
        return QString("东偏北%1").arg(int(angleDeg - 315));
}

QString Widget::targetToDisplayString(const Target& target)
{
    QPointF pos = QPointF(target.x, target.y);
    QString directionStr = convertDirection(target.angle);

    return QString("(%1, %2) | %3 | %4km/h")
        .arg(qFloor(pos.x()))
        .arg(qFloor(pos.y()))
        .arg(directionStr)
        .arg(QString::number(target.speed, 'f', 0)); // 取整显示速度
}


void Widget::refreshScrollList()
{
    // 清空原有控件
    QLayoutItem *child;
    while ((child = scrollLayout->takeAt(0)) != nullptr) {
        if (child->widget()) {
            child->widget()->deleteLater();
        }
        delete child;
    }

    // 遍历 map 添加最新内容
    for (const Target &target : radarDataMap.values()) {
        QString text = targetToDisplayString(target);
        QLabel *itemLabel = new QLabel(text);
        itemLabel->setStyleSheet("background-color: rgba(255,255,255,50); border:1px solid #ccc; border-radius:5px; padding:4px;");
        scrollLayout->addWidget(itemLabel);
    }
}

// void printTargetInfo(const Target &target)
// {
//     qDebug() << "-------- Target Info --------";
//     qDebug() << "ID:" << target.id;
//     qDebug() << "Relative Distance:" << target.relDistance;
//     qDebug() << "Angle (radians):" << target.angle;
//     qDebug() << "Speed:" << target.speed;
//     qDebug() << "Color:" << target.color.name();

//     qDebug() << "History:";
//     for (const QPointF &pt : target.history) {
//         qDebug() << "   (" << pt.x() << "," << pt.y() << ")";
//     }
//     qDebug() << "-----------------------------";
// }

double Widget::calculateRelativeDistanceQt(
    const QPointF& m_center, // 中心点（使用Qt的QPointF）
    double m_radius,         // 半径
    const QPointF& newPoint // 新点坐标（使用Qt的点类型）
    ) {
    // 计算坐标差值（使用QPointF的成员函数）
    const double dx = newPoint.x() - m_center.x();
    const double dy = newPoint.y() - m_center.y();

    // 计算欧氏距离（使用Qt的平方根函数）
    const double distance = qSqrt(dx*dx + dy*dy);

    // 返回限制后的相对距离（使用标准库限制范围）
    return std::min<double>(distance / m_radius, 1.0);
}

void Widget::deletePointInMap()
{
    radarDataMap.remove(radar->getid()); // 删除点
    refreshScrollList();
}

void Widget::setImLabelText(const QString &text)
{
    if (ImLable) {  // 确保标签对象存在
        ImLable->setText(text);
        ImLable->setStyleSheet("background-color: rgba(255, 255, 255, 180);"  // 高亮显示
                               "border: 2px solid #FF0000;"
                               "border-radius:5px;"
                               "padding:4px;");

        // 添加3秒后恢复样式的动画
        QTimer::singleShot(3000, [this](){
            ImLable->setStyleSheet("background-color: rgba(255, 255, 255, 50);"
                                   "border:1px solid #ccc;"
                                   "border-radius:5px;"
                                   "padding:4px;");
        });
    }
}

void Widget::updateRadarData(Target &point)
{
    QPointF pos = QPointF(point.x, point.y);
    pos.setX(pos.x() / radar->getradius());
    pos.setY(pos.y() / radar->getradius());
    const double dx = qFloor(pos.x()) - radar->getcenter().x();
    const double dy = qFloor(pos.y()) - radar->getcenter().y();
    // 修正百分比距离
    point.relDistance = (qFloor(qSqrt(dx*dx + dy*dy)) % radar->getradius() * 1.0) / radar->getradius();
    qDebug() << point.relDistance << ", " << point.angle;
    radarDataMap[point.id] = point; // 添加新的点
    //printTargetInfo(point);
    refreshScrollList();
}

void Widget::updatePointData(long id, Target &point)
{
    if (point.id == -1)
        radarDataMap.remove(id);
    else
        radarDataMap[id] = point;
}

